package algorithmic_data_structure.动态规划;

public class 最长公共子序列 {
    public static int longestCommonSubsequence2(String s1, String s2) {
        if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
            return 0;
        }
        char[] str1 = s1.toCharArray();
        char[] str2 = s2.toCharArray();
        int[][] dp = new int[str1.length][str2.length];
        dp[0][0] = str1[0] == str2[0] ? 1 : 0;
        for (int i = 1; i < str1.length; i++) {
            dp[i][0] = str1[i] == str2[0] ? 1 : dp[i-1][0];
        }
        for (int j = 1; j < str2.length; j++) {
            dp[0][j] = str1[0] == str2[j] ? 1 : dp[0][j-1];
        }
        for (int i = 1; i < str1.length; i++) {
            for (int j = 1; j < str2.length; j++) {
                dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
                if (str1[i] == str2[j]){
                    dp[i][j] = Math.max(dp[i][j],dp[i-1][j-1]+1);
                }
            }
        }
        return dp[str1.length-1][str2.length-1];
    }
    public static int longestCommonSubsequence1(String s1, String s2) {
        if (s1 == null || s2 == null || s1.length() == 0 || s2.length() == 0) {
            return 0;
        }
        //从后面开始推
        return process(s1.toCharArray(),s1.length()-1,s2.toCharArray(),s2.length()-1);
    }

    private static int process(char[] str1, int index1, char[] str2, int index2) {
        if (index1 == index2 && index1 == 0){
            return str1[index1] == str2[index2] ? 1 : 0;
        }
        if (index1 == 0){
            return process(str1,index1,str2,index2-1);
        }
        if (index2 == 0){
            return process(str1,index1-1,str2,index2);
        }
        int p = process(str1,index1-1,str2,index2-1);
        return str1[index1] == str2[index2] ? p + 1 : p;
    }

}
